package com.gilight.base.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.gilight.base.dto.CodeGeneratorDto;
import com.gilight.base.service.CodeGeneratorService;
import com.gilight.base.util.ExportExcel;
import com.gilight.base.util.ZipUtil;
import com.google.common.collect.Lists;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@Service
public class CodeGeneratorServiceImpl implements CodeGeneratorService {

    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.driverClassName}")
    private String driverName;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    @Override
    public String generate(CodeGeneratorDto codeGeneratorDto) {
        String dictionary = "d:\\temp\\"+ UUID.randomUUID();
        //表名
        String[] tableName = codeGeneratorDto.getTableNames().toArray(new String[0]);
        // 代码生成器
//        String projectPath = System.getProperty("user.dir");
        String templatePath = "/templates/mapper.xml.ftl";
        AutoGenerator mpg = new AutoGenerator().setGlobalConfig(
            // 全局配置
            new GlobalConfig()
                .setOutputDir(dictionary)
                .setAuthor(codeGeneratorDto.getAuthor())
                .setOpen(false)
                .setBaseResultMap(true)
                .setBaseColumnList(true)
        ).setDataSource(
            // 数据源配置
            new DataSourceConfig()
                .setUrl(url)
                .setDriverName(driverName)
                .setUsername(username)
                .setPassword(password)
        ).setPackageInfo(
            // 包配置
            new PackageConfig()
                .setParent(codeGeneratorDto.getPackageName())
                .setMapper(codeGeneratorDto.getMapperPackage())
                .setEntity(codeGeneratorDto.getEntityPackage())
                .setService(codeGeneratorDto.getServicePackage())
                .setServiceImpl(codeGeneratorDto.getServiceImplPackage())
        ).setCfg(
                new InjectionConfig() {
                    @Override
                    public void initMap() {
                    }
                }.setFileOutConfigList(Lists.newArrayList(new FileOutConfig(templatePath) {
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                        // 自定义输出文件名,如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                        return dictionary + "/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                    }
                }))
        ).setStrategy(
            // 策略配置
            new StrategyConfig()
                .setNaming(NamingStrategy.underline_to_camel)
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setRestControllerStyle(true)
                .setInclude(tableName)
                .setControllerMappingHyphenStyle(true)
        ).setTemplate(
            // 配置模板
            new TemplateConfig().setXml(null)
        ).setTemplateEngine(new FreemarkerTemplateEngine());

        mpg.execute();
        return dictionary;
    }

    @Override
    public ResponseEntity<byte[]> zipAndDownload(String path) {
        //压缩文件
        File file = new File(path + ".zip");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            ZipUtil.toZip(path, fos,true);
            //下载
            byte[] bytes = FileUtil.readAsByteArray(file);
            return ExportExcel.sendToWeb(bytes, "导出代码.zip");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
